<?php
/**
 * Created by PhpStorm.
 * User: guanfangge
 * Date: 4/26/22
 * Time: 10:51 AM
 */
namespace App\HttpController\Admin;

use App\HttpController\Base;
use EasySwoole\Component\AtomicManager;
use EasySwoole\Component\ChannelLock;
use EasySwoole\Http\Request;
use EasySwoole\HttpAnnotation\AnnotationTag\Param;
use EasySwoole\Jwt\Jwt;

use App\Models\User;
use EasySwoole\Http\AbstractInterface\Controller;

use co;
use EasySwoole\Component\CoroutineRunner\Runner;
use EasySwoole\Component\CoroutineRunner\Task;



class Login extends Controller
{
    /**
     * @Param(name="name",required="",lengthMax="255")
     * @Param(name="password",required="",type="int")
     */
    public function login()
    {
        $data = $this->request()->getRequestParam();
        $user = User::create()->where(['name'=>$data['name'],'password'=>md5($data['password'])])->get();
        if(empty($user)){
            return $this->writeJson(0,$user,'用户密码错误');
        }
        $jwtObject = Jwt::getInstance()
            ->setSecretKey('easyswoole') // 秘钥
            ->publish();
        $jwtObject->setAlg('HMACSHA256'); // 加密方式
        $jwtObject->setAud('user'); // 用户
        $jwtObject->setExp(time()+3600*1000); // 过期时间
        $jwtObject->setIat(time()); // 发布时间
        $jwtObject->setIss('easyswoole'); // 发行人
        $jwtObject->setJti(md5(time())); // jwt id 用于标识该jwt
        $jwtObject->setNbf(time()+60*5); // 在此之前不可用
        $jwtObject->setSub('主题'); // 主题
        // 自定义数据
        $jwtObject->setData(json_encode($user));
        // 最终生成的token
        $token = $jwtObject->__toString();
        $data['user']  = $user;
        $data['token'] = $token;
        return $this->writeJson(1,$data,'登录成功');
    }

    public function getToken()
    {
        $token = $this->request()->getHeader('token');
        try {
            $jwtObject = Jwt::getInstance()->decode($token[0]);

            $status = $jwtObject->getStatus();

            // 如果encode设置了秘钥,decode 的时候要指定
            //$status = $jwtObject->setSecretKey('easyswoole')->decode($token[0]);

            switch ($status)
            {
                case  1:
                    return $this->writeJson(1,json_decode($jwtObject->getData(),true));
                    break;
                case  -1:
                    return $this->writeJson(0,'token无效');
                    break;
                case  -2:
                    return $this->writeJson(0,'token值过期');
                    break;
            }
        } catch (\EasySwoole\Jwt\Exception $e) {
            return $this->writeJson(0,$e->getMessage());
        }
    }
    public function runner()
    {
        $runner = new Runner(1024);
        $runner->setOnException(function(\Throwable  $e, $task){
            echo $e->getMessage();
            echo PHP_EOL;
        });

        $max = 1024;
        $allTask = [];
        while($max>0){

            $task = new Task(function() use ($max) {
                $client = new \EasySwoole\HttpClient\HttpClient('http://www.autoserve.com.cn/Home/Product/lists/cateid/3.html');
                echo $max .PHP_EOL;
            //    co::sleep(1);
                return $client->get();
                // 将设这是一个curl爬取任务 return 爬取结果 可以在外部获取
               // return 'ok';
            });
            $runner->addTask($task);
            $allTask[] = $task;
            $max--;
            var_dump($max);
        }

        $runner->start(1);// 最长执行1秒  总共投递了30个 最大并发10个 需要3秒执行完，所以会有一部分将被丢弃  看下方参数说明列表

        $task->setOnSuccess(function (){
            var_dump('ok');
        });
        $task->setOnFail(function (){
            var_dump('error');
        });
        foreach($allTask as $key => $task){
            var_dump($task->getResult());
        }
    }
    function atomic()
    {

        AtomicManager::getInstance()->add('second',0);
        $atomic = AtomicManager::getInstance()->get('second');
        $atomic->add(1);
        $this->response()->write($atomic->get());
        // TODO: Implement index() method.
    }

    public function ChannelLock()
    {
       $look =  ChannelLock::getInstance()->lock('a');
       var_dump($look);
       co::sleep(1);
       $look = ChannelLock::getInstance()->unlock('a');
       var_dump($look);

    }
}